package com.hll.servlet.user;

import com.hll.pojo.User;
import com.hll.service.user.UserService;
import com.hll.service.user.UserServiceImpl;
import com.hll.utils.Constants;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * Controller层,调用service层
 *
 * @author: Mr.Hu
 * @create: 2021-03-07 18:27
 */
public class LoginServlet extends HttpServlet {
  @Override
  protected void doGet(HttpServletRequest req, HttpServletResponse resp)
      throws ServletException, IOException {
    // 获取用户名和密码
    String userCode = req.getParameter("userCode");
    String userPassword = req.getParameter("userPassword");
    // 调用service方法，进行用户匹配
    UserService userService = new UserServiceImpl();
    User user = userService.login(userCode, userPassword);
    if (null != user) { // 登录成功
      // 放入session
      req.getSession().setAttribute(Constants.USER_SESSION, user); // 存了对象
      // 页面跳转（frame.jsp）
      resp.sendRedirect(req.getContextPath() + "/jsp/frame.jsp");
    } else {
      // 页面跳转（login.jsp）带出提示信息--转发
      req.setAttribute("error", "用户名或密码不正确"); // 用完即丢存request
      req.setAttribute(Constants.USER_NAME, userCode); // 我希望错误后只删掉密码栏
      // 不需要contextPath+..
      req.getRequestDispatcher("/login.jsp").forward(req, resp); // 如果是重定向,那么request存活期已过
    }
  }

  @Override
  protected void doPost(HttpServletRequest req, HttpServletResponse resp)
      throws ServletException, IOException {
    doGet(req, resp);
  }
}
